package com.seedeer.framework.aspectj;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.seedeer.common.util.AuthorityUtils;
import com.seedeer.common.util.ServletUtils;
import com.seedeer.framework.aspectj.lang.annotation.Log;
import com.seedeer.pms.model.PmsAccountInfo;
import com.seedeer.project.domain.entity.ActionLog;
import com.seedeer.project.service.system.IActionLogService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 操作日志记录处理
 *
 * @author wangqiang
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private IActionLogService actionLogService;

    // 配置织入点
    @Pointcut("@annotation(com.seedeer.framework.aspectj.lang.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 记录数据库日志
            ActionLog actionLog = new ActionLog();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            HttpServletRequest request = ServletUtils.getRequest();
            if (method != null) {
                Log log = method.getAnnotation(Log.class);
                if (null != log) {
                    actionLog.setOperatorType(log.operatorType());
                    if (log.isSaveRequestData()) {
                        actionLog.setRequestParam(JSONUtil.toJsonStr(request.getParameterMap()));
                    }
                }
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                if (null != apiOperation) {
                    actionLog.setActionName(apiOperation.value());
                }
            }

            actionLog.setRequestUrl(request.getRequestURI());
            actionLog.setRequestMethod(request.getMethod());
            actionLog.setResponseBody(JSONUtil.toJsonStr(jsonResult));
            if (e != null) {
                actionLog.setException(StringUtils.substring(e.getMessage(), 0, 2000));
            }

            // 获取当前的用户
            PmsAccountInfo currentUser = AuthorityUtils.getCurrentUser();
            if (currentUser != null) {
                actionLog.setOperatorCode(currentUser.getUserCode());
            }
            actionLog.setActionTime(LocalDateTime.now());
            // 异步保存数据库
            ThreadUtil.execAsync(() -> {
                actionLogService.save(actionLog);
            });
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage(), e);
        }
    }
}